from odoo import api, fields, models
from odoo.exceptions import UserError

ADDRESS_TYPE = [('residential', '个人'), ('commercial', '公司')]


class RpInvoiceAddressTran(models.TransientModel):
    _name = 'rp.invoice.address.tran'
    _description = '订单发票地址填充'

    related_model_id = fields.Many2one(string='关联模型', comodel_name='ir.model')
    invoice_state_id = fields.Many2one(string='发票邮寄省', comodel_name='res.country.state', store=True)
    invoice_city_id = fields.Many2one(string='发票邮寄市', comodel_name='res.city', store=True)
    invoice_receive_street = fields.Char(string='发票邮寄街道1', tracking=True)
    invoice_receive_street2 = fields.Char(string='发票邮寄街道2', tracking=True)
    invoice_first_name = fields.Char(string='发票邮寄人名', tracking=True)
    invoice_last_name = fields.Char(string='发票邮寄人姓', tracking=True)
    invoice_phone_number = fields.Char(string='发票邮寄人电话', tracking=True)
    invoice_postal_code_id = fields.Many2one(string='发票邮递邮编', comodel_name='rp.postal.code', tracking=True)
    invoice_address_type = fields.Selection(string='发票邮寄地址类型', selection=ADDRESS_TYPE, default=ADDRESS_TYPE[0][0], tracking=True)
    invoice_email = fields.Char(string='发票邮寄人邮箱', tracking=True)
    invoice_company_name = fields.Char(string='发票邮寄地址公司名称', tracking=True)

    """
    Native
    """

    @api.constrains('invoice_state_id', 'invoice_city_id', 'invoice_receive_street', 'invoice_receive_street2', 'invoice_first_name', 'invoice_last_name',
                    'invoice_phone_number', 'invoice_postal_code_id', 'invoice_address_type', 'invoice_email')
    def check_data_complete(self):
        for record in self:
            if all([record.invoice_state_id, record.invoice_city_id, record.invoice_receive_street, record.invoice_receive_street2, record.invoice_first_name, record.invoice_last_name,
                    record.invoice_phone_number, record.invoice_postal_code_id, record.invoice_address_type, record.invoice_email]):
                if record.invoice_address_type == 'commercial' and not record.invoice_company_name:
                    raise UserError('请填写发票邮寄地址的公司名称！')
            else:
                raise UserError('请检查数据是否完整！')

    def default_get(self, fields_list):
        res = super(RpInvoiceAddressTran, self).default_get(fields_list)
        if 'model_id' in self.env.context:
            res['related_model_id'] = self.env.context.get('model_id')
        return res

    """
    Onchange
    """

    @api.onchange('invoice_postal_code_id')
    def onchange_on_invoice_postal_id(self):
        """填入发票邮编自动填充发票省，市"""
        if self.invoice_postal_code_id:
            self.update({'invoice_state_id': self.invoice_postal_code_id.state_id.id,
                         'invoice_city_id': self.invoice_postal_code_id.city_id.id})

    def gene_invoice(self):
        # 写入订单发票地址
        active_ids = self.env.context.get('active_ids')
        advanced_records_ids = self.env[self.related_model_id.model].search([('id', 'in', active_ids)])
        advanced_model_id = self.env['ir.model'].search([('model', '=', self.related_model_id.model)])
        # 写入地址，发票字段固定是这样
        for record in advanced_records_ids:
            record.write({
                'invoice_postal_code_id': self.invoice_postal_code_id.id,
                'invoice_state_id': self.invoice_state_id.id,
                'invoice_city_id': self.invoice_city_id.id,
                'invoice_receive_street': self.invoice_receive_street,
                'invoice_receive_street2': self.invoice_receive_street2,
                'invoice_first_name': self.invoice_first_name,
                'invoice_last_name': self.invoice_last_name,
                'invoice_phone_number': self.invoice_phone_number,
                'invoice_address_type': self.invoice_address_type,
                'invoice_email': self.invoice_email,
                'need_invoice': True,
                'invoice_company_name': self.invoice_company_name
            })
        # 支付单生成发票
        rp_payments_ids = self.env['rp.payment'].search([('advance_document_id.field_record_id', 'in', advanced_records_ids.ids), ('advance_document_id.field_name_id', '=', advanced_model_id.id)])  # 支付单
        rp_payments_ids[0].gene_invoice(advanced_records_ids)  # 调用一次方法即可，前置单据生成发票
        actions = self.env['ir.actions.act_window'].search([('res_model', '=', self.related_model_id.model)], limit=1)
        if actions:
            return actions.read()[0]
        return {}


class RpShipOrderInvoiceAddressTran(models.TransientModel):
    _name = 'rp.ship.order.invoice.address.tran'
    _description = '保持源系统一致（重新安装系统可删除）'
    inherit = ['rp.invoice.address.tran']
